package com.jingming.consult

import android.annotation.SuppressLint
import android.content.Intent
import android.os.AsyncTask
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.webkit.WebChromeClient
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.github.lzyzsd.jsbridge.CallBackFunction
import com.github.lzyzsd.jsbridge.DefaultHandler
import com.hjq.toast.ToastUtils
import com.jingming.consult.adapters.MainFragmentAdapter
import kotlinx.android.synthetic.main.activity_main.*

/**
 * 主页面
 */
class MainActivity : AppCompatActivity() {
    val TAG = "MainActivity"
    var fragments: MutableList<Fragment> = ArrayList()
    var handler: Handler = @SuppressLint("HandlerLeak")
    object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
        }
    }

    // 弹出框
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.e(TAG, "oncreate")
        setContentView(R.layout.activity_main)
        initView()
        handler.sendEmptyMessage(1)
        handler.post(Runnable {

        })
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        Log.e(TAG, "onNewIntent")
    }

    private fun initView() {
        bnve.enableAnimation(false);
        bnve.setupWithViewPager(viewpager, false)
        viewpager.adapter = MainFragmentAdapter(supportFragmentManager)
        webView.setDefaultHandler(DefaultHandler())
        webView.webChromeClient = WebChromeClient()
        webView.loadUrl("file:///android_asset/jsbridge.html")
        webView.registerHandler("submitFromWeb") { data:String, function ->
            Log.e("TAG", "js返回：" + data);
            //显示js传递给Android的消息
            ToastUtils.show("js返回:" + data)
            //Android返回给JS的消息
            function.onCallBack("我是js调用Android返回数据：" + et.getText().toString());
        }
        bt.setOnClickListener {
            //调用js中的方法（必须和js中的handlerName想同）
            webView.callHandler("functionInJs",et.text.toString(), CallBackFunction { it ->
                Log.e("TAG", "onCallBack:" + it);
                if (!TextUtils.isEmpty(it))
                ToastUtils.show(it)
            })
        }
    }


    override fun onStart() {
        super.onStart()
        Log.e(TAG, "onStart")
    }

    override fun onRestart() {
        super.onRestart()
        Log.e(TAG, "onRestart")
    }

    override fun onResume() {
        super.onResume()
        Log.e(TAG, "onResume")
    }

    override fun onPause() {
        super.onPause()
        Log.e(TAG, "onPause")
    }

    override fun onStop() {
        super.onStop()
        Log.e(TAG, "onStop")
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.e(TAG, "onDestroy")
    }

}
